"""
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    created by lei.chang on '13/10/2023'
    comment: 生成器逻辑(案例编号，评测记录编号)
"""
import random
import datetime
from config import Config
from project.lib.constant import ASC_SERIES, INITIAL_TIME
from project.lib.decorator import with_async_redis

# 服务流程编号
FLOW_CODE_COUNTER = f'{Config.PROJECT_NAME}:flow_code_counter'

# 评测记录编号
FLOW_RECORD_CODE_COUNTER = f'{Config.PROJECT_NAME}:flow_record_code_counter'


class CodeGenerator:
    """  编码生成类
    """
    @staticmethod
    @with_async_redis()
    async def generate_flow_code(rds=None) -> str:
        """ 生成案例编号(6位)
            算法设计: 99案例/天, 支持9-10年
        :return:
        """
        fix = random.choice(ASC_SERIES[10:])

        now = datetime.datetime.now()
        days = (now - INITIAL_TIME).days

        count = await rds.incr(FLOW_CODE_COUNTER)

        code = f'{fix}' \
               f'{ASC_SERIES[(days // 99) % 36]}' \
               f'{(str(days % 100)).zfill(2)}' \
               f'{str(count % 100).zfill(2)}'

        return code

    @staticmethod
    @with_async_redis()
    async def generator_flow_record_code(flow_code, rds=None):
        """ 生成评测记录编号(14位)
            算法设计: 9999/每个案例/天 支持99-100年
        :param flow_code: 服务流程编号
        :param rds:
        :return:
        """
        count = await rds.hget(FLOW_RECORD_CODE_COUNTER, flow_code)
        count = int(count) if count else 0
        count += 1
        await rds.hset(FLOW_RECORD_CODE_COUNTER, flow_code, str(count))

        now = datetime.datetime.now()
        days = (now - INITIAL_TIME).days

        code = f'{flow_code}' \
               f'{ASC_SERIES[(days // 999) % 36]}' \
               f'{(str(days % 1000)).zfill(3)}' \
               f'{str(count % 10000).zfill(4)}'

        return code


if __name__ == '__main__':

    pass


